/**
 * Copyright 厦门中软海晟信息技术有限公司 版权所有 违者必究 2018
 */
package com.opencvjava.support.other;

import org.opencv.core.Mat;

import javax.swing.JComponent;
import javax.swing.JDialog;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import static com.opencvjava.support.util.CvUtils.mat;
import static com.opencvjava.support.util.ImageUtils.mat2BufferedImage;

/**
 *
 *@author : sunzb(sunzb@hsit.com.cn)
 *@date: 2018/6/21
 */
public class ImgDialog extends JComponent {
    private static int imshowIndex = 0;
    private static int Y_OFFSET = 0;
    private BufferedImage image;
    private int w;
    private int h;
    private String title;

    public ImgDialog(String title, String fold, String fileName) {
        this(title, mat(fold, fileName));
    }

    public ImgDialog(String title, String fileName) {
        this(title, mat(fileName));
    }

    public ImgDialog(String title, Mat mat) {
        this(title, mat2BufferedImage(mat));
    }

    public ImgDialog(String title, BufferedImage image) {
        this.image = image;
        w = this.image.getWidth();
        h = this.image.getHeight();
        w = w < 100 ? 100 : w;
        h = h < 100 ? 200 : h;
        this.title = title;
        imshowIndex++;
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        if(image == null)  {
            g2d.setPaint(Color.BLACK);
            g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
        } else {
            g2d.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
        }
    }

    public void createWin() {
        JDialog ui = new JDialog();
        ui.setTitle(title);
        ui.getContentPane().setLayout(new BorderLayout());
        ui.getContentPane().add(this, BorderLayout.CENTER);
        ui.setSize(w + 2, h + 2);
        if (imshowIndex != 0 && imshowIndex % 8 == 0) {
            Y_OFFSET -= 400;
        }
        ui.setBounds(imshowIndex * 50, Y_OFFSET + imshowIndex * 50, w, h);
        ui.setVisible(true);
    }

    public void imshow() {
        createWin();
        this.repaint();
    }
}
